//映入axios相关
import axios from "axios";
import settle from "axios/lib/core/settle";
import buildURL from "axios/lib/helpers/buildURL";
import buildFullPath from "axios/lib/core/buildFullPath"; //解决axios0.19.0以上版本无法请求问题
import config from "../uni_modules/uview-ui/libs/config/config";

//根据环境变量获取api地址
// let baseURL = process.env.config[process.env.UNI_SCRIPT].VITE_BASE_API;
// let evnName = process.env.config[process.env.UNI_SCRIPT] 获取当前处于哪个开发环境

//解决uniapp 适配axios请求，避免报adapter is not a function错误
axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		const fullurl = buildFullPath(config.baseURL, config.url);
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(fullurl, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config,
				};

				settle(resolve, reject, response);
			},
		});
	});
};

axios.interceptors.request.use(
	(config) => {
		console.log("发送了请求");
		// 允许携带cookie
		config.withCredentials = true;
		return config;
	},
	(error) => {
		// 对请求错误做些什么
		console.log(error);
		return Promise.reject(error);
	}
)

// 各种类型，进行适配，假如一致则直接返回数据内容
const types = [
	"application/octet-stream"
]

axios.interceptors.response.use(
	(response) => {
		console.log("axios----->响应suc----------------》");
		const header = response.header
		const res = response.data;
		// 适配各类型响应头
		for (var i = 0; i < types.length; i++) {
			// console.log(header['Content-Type'].includes(types[i]));
			if (header['Content-Type'].includes(types[i])) {
				console.log(`适配成功！${types[i]}类型将之间返回内容`);
				return res;
			}
		}
		if (res.code !== 20000) {
			Message({
				message: res.message || "Error",
				type: "error",
				duration: 5 * 1000,
			});
			if (
				res.code === 50008 ||
				res.code === 50012 ||
				res.code === 50014 ||
				res.code === 50017
			) {
				// code异常处理
			}
			if (res.code === 50000) {
				wx.showToast({
					title: res.message,
					icon: "none",
					duration: 1000
				});
			}
			// 简单的拦截，如果code不与上面一致直接放行
			return res;
		} else {
			return res;
		}
	},
	(err) => {
		console.log("axios----->响应err----------------》");
		// console.log("err" + err); // for debug
		Message({
			message: err.message,
			type: "error",
			duration: 5 * 1000,
		});
		return Promise.reject(err);
	}
);

axios.defaults.baseURL = "http://localhost:9000/"

export default axios;